<?php

namespace App\Http\Controllers\Web;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Chat;
use App\Models\ChatRoom;
use App\Traits\BaseFun;
use App\Repositories\UserRepository;
class ChatController extends Controller
{
    //
    public function __construct(UserRepository $UserRepository)
    {
        $this->UserRepository=$UserRepository;
    }

    public function index(Request $request){
        $chatid=$request->input('chatid');
        $chatinfo= $this->UserRepository->info($chatid);
        $userinfo=$request->session()->get('userinfo');
        //查找房间号
        $room=ChatRoom::where(['from_id'=>$userinfo['id'],'to_id'=>$chatid])->first();
        $room2=ChatRoom::where(['from_id'=>$chatid,'to_id'=>$userinfo['id']])->first();
        
        if($room||$room2){
            $roomt=$room?$room:$room2;
            return BaseFun::jsonWebReturn(['code'=>200,'data'=>$roomt,'msg'=>'ok']);
        }else{
            //创建房间
            $data['from_id']=$userinfo['id'];
            $data['to_id']=$chatid;
            $data['room_name']=$userinfo['nickname']."和".$chatinfo['nickname']."在聊天~~~~";
            // $sys = new ChatRoom();
            $id =  ChatRoom::create($data)->id;
            return BaseFun::jsonWebReturn(['code'=>200,'data'=>['id'=>$id],'msg'=>'ok']);
        }
    }
    
    public function chat(Request $request,$id){
        $room=ChatRoom::where('id',$id)->first();
        $userinfo=$request->session()->get('userinfo');
        if($room['to_id']==$userinfo['id']){
            $objectid=$room['from_id'];
        }else{
            $objectid=$room['to_id'];
        }
        $object=$this->UserRepository->info($objectid);
        $chatList=Chat::where('room_id',$id)->get();
        $res['userinfo']=$userinfo;
        $res['chatList']=$chatList;
        return view('web.chat',['userinfo'=>$userinfo,'chatList'=>$chatList,'room'=>$room,'object'=>$object]);
        // return BaseFun::jsonWebReturn(['code'=>200,'data'=>$res,'msg'=>'ok']);
    }
}